//npm install node-rest-client --save-dev
var colors = require( "colors")
const fs = require('fs');
const http = require('http');
const iconv = require('iconv-lite');
const querystring = require('querystring')
const restApi = require('./rest-client')
var multiparty = require('multiparty')

const  isJson = function(str) {  
    try {  
        JSON.parse(str);  
    } catch (e) {  
        return false;  
    }  
    return true;  
} 
const hostname = '192.168.1.2';
const port = 3000;

const server = http.createServer((req, res) => {
  var ContentType = req.rawHeaders[ req.rawHeaders.indexOf('Content-Type') + 1 ]
  console.log( '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>  req info >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'.yellow )
  var formData = ''
  var arr = [];
    req.on("data",function(chunk){
      //console.log('req chunk:\n' + chunk.toString())
        arr.push( chunk );
    });
    var form = new multiparty.Form();
    form.parse(req, function ( err, fields, files ) {
      if( err ) console.log('formDataErr:\n'.red, err.toString())
      if( fields ){
        for( o in fields ){ fields [ o ] = fields [ o ] [ 0 ] }
        formData = fields
      }

      var data= Buffer.concat(arr).toString();
      if( isJson(data)) var ret = JSON.parse(data)
      console.log( ret || data || formData || 'no data')
      req.body = formData || ret || data || null;
      console.log(  '=======================================\n[' + req.method + '] ', req.url, /*'\nreq.headers:', req.headers,*/'\nbody:', req.body, '\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<'.green )
        //next();
      
      res.setHeader('Content-Type', 'application/json');
      restApi.fatch({
        method: req.method,
        url : req.url,
        data: req.body,
        succ: function(data){
          if(data) var jsonData = JSON.parse( data )
          res.statusCode = jsonData ? jsonData.ssrsc : 404;
          res.end(data)
        }
      });

      //if(files) console.log('files:\n', files)
    });
    req.on("end",function(){
      //console.log(req)

      //const postData = querystring.parse(data)
      //console.log(postData)
    })

});

server.listen(port, hostname, () => {
  console.log(`服务器运行在 http://${hostname}:${port}/`);
});




/*
var Client = require('node-rest-client').Client
function locate(args) {
  args.url || console.log('no url')
    var client = new Client()
    //console.log(client)
    var postData = {
        data: args.data||null,
        headers: { "Content-Type": "application/json" }
    };

    // registering remote methods 
    client.registerMethod("postMethod", args.url, "POST");

    client.methods.postMethod(postData, function (data, response) {
        // parsed response body as js object
        data.length === 0 && ( data = '{ "success": "false", "code": "-1", "msg:", "CRM服务器可能睡着了!"}')
        console.log(data.toString());
      typeof cb === 'function' && cb(data.toString())
        // raw response 
        //console.log(response);
    });
}*/
/*
locate({
  url: "http://192.168.1.13:8180/TYCRM/BaseMyDiary/loadProjInDiary",
  data: {
    userid:111,
    pageIndex:'',
    pageSize:10,
    date:2017-03-22
  }
})
*/